<template>
  <div class="container">
    <div class="add">
      <el-dropdown
        szie="small"
        trigger="click"
        @command="addPlan"
        v-if="!hideBtn"
      >
        <el-button
          size="mini"
          class="el-icon-plus"
          type="primary"
          style="margin: 0 -10px 0 10px"
        >
          新建
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item :command="0">大修计划</el-dropdown-item>
          <el-dropdown-item :command="1">试验计划</el-dropdown-item>
          <el-dropdown-item :command="2">计划性检修计划</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <base-table :tableSetting="baseTableSetting"></base-table>
    <dialogPublic
      :title="title"
      :show.sync="show"
      @doSubmit="doSubmit"
      @doClose="() => (show = false)"
      :noFootBtn="hideBtn"
      width="70%"
    >
      <template v-if="show">
        <editForm
          v-if="title == '大修计划'"
          :formConfig="overhaulConfig"
          ref="editForm"
          :formData="editFormData"
        ></editForm>
        <editForm
          v-if="title != '大修计划'"
          :formConfig="formConfig"
          ref="editForm"
          :formData="editFormData"
        ></editForm>
      </template>
    </dialogPublic>
  </div>
</template>

<script>
import { getPresetParamsApi } from "@/api/common";
export default {
  props: {
    depts: {
      type: Object,
      default: () => {
        return {};
      },
    },
    hideBtn: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      title: "",
      show: false,
      //基本参数
      baseTableSetting: {
        indexShow: true,
        column: [
          {
            label: "工作类别",
            textAlign: "center",
            prop: "jobType",
            formatter: (row) => {
              return this.$store.getters.fineDirtDataName(
                "plan_package_type",
                row.jobType
              );
            },
          },
          {
            label: "设备管理单位",
            textAlign: "center",
            prop: "deptManageName",
          },
          {
            label: "设备名称",
            textAlign: "center",
            prop: "level",
            formatter: (row) => {
              return row.equipments.map((item) => item.equipmentName).join(",");
            },
          },
          {
            label: "工作内容",
            textAlign: "center",
            prop: "content",
          },
          {
            label: "计划起止时间",
            textAlign: "center",
            prop: "startEndTime",
            formatter: (row) => {
              return `${row.startTime}~${row.endTime}`;
            },
          },
          {
            label: "主办单位",
            textAlign: "center",
            prop: "organizerName",
          },
          {
            label: "操作",
            textAlign: "center",
            type: "button",
            buttonArr: [
              {
                text: "详情",
                isShow: () => {
                  return this.hideBtn;
                },
                methods: (row, index) => {
                  this.editBaseParam(row);
                },
              },
              {
                text: "编辑",
                isShow: () => {
                  return !this.hideBtn;
                },
                methods: (row, index) => {
                  this.rowIndex = index;
                  this.editBaseParam(row);
                },
              },
              {
                text: "删除",
                isShow: () => {
                  return !this.hideBtn;
                },
                methods: (row, index) => {
                  this.$confirm("确定要删除该条数据吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(() => {
                      this.baseTableSetting.data.splice(index, 1);
                    })
                    .catch((e) => {});
                },
              },
            ],
          },
        ],
        data: [],
        noBorderRight: false,
        autoHeight: true,
        //height: 400,
      },
      //弹出框表单配置信息
      formConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            propArr: "deptArr",
            idsStr: "deptManage",
            // level: "3",
            multiple: false, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "dept-select", //类型
            trigger: "change",
            methods: (data, formData) => {},
            span: 8,
            required: true,
            disabled: false,
          },
          {
            label: "设备名称",
            prop: "equipmentName",
            propArr: "equipmentArr",
            idsStr: "equipmentId",
            filterConfig: ["filterManagerUnit"],
            managerUnit: [],
            multiple: true, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "device-select", //类型
            trigger: "change",
            beforeMethod: (formData, item) => {
              if (formData.deptManageName && formData.deptManageName != "") {
                item.managerUnit = [formData.deptManage];
                return true;
              } else {
                this.$message.warning("请先选择设备管理单位");
                return false;
              }
            },
            methods: (data, formData) => {
              let arr = data.map((item) => {
                const obj = {
                  equipmentId: item.id,
                  equipmentName: item.name,
                };
                return obj;
              });
              this.$refs.editForm.setFormItem("equipments", arr);
            },
            span: 8,
            required: true,
            disabled: false,
          },
          {
            label: "计划起止时间",
            prop: "planStartTime",
            type: "datetimerange",
            required: true,
            disabled: false,
            span: 8,
            methods: (val) => {
              let timers = new Date(val[0]).getTime() - 7 * 24 * 60 * 60 * 1000;
              let remindTime = this.$utils.TimeFormat(timers, 3);
              this.$refs.editForm.setFormItem("startTime", val[0]);
              this.$refs.editForm.setFormItem("endTime", val[1]);
              this.$refs.editForm.setFormItem("remindTime", remindTime);
            },
          },
          {
            label: "提醒时间",
            prop: "remindTime",
            type: "datetime",
            isHide: false,
            disabled: false,
            required: true,
            min: 0,
            span: 8,
          },
          {
            label: "工作内容",
            prop: "content",
            type: "textarea",
            required: true,
            span: 24,
            rows: 6,
          },
          {
            label: "备注",
            prop: "desc",
            type: "textarea",
            disabled: false,
            span: 24,
            rows: 6,
          },
        ],
      },
      overhaulConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName",
            propArr: "equipmentArr",
            idsStr: "equipmentId",
            filterConfig: ["hasManagerUnit"],
            multiple: false, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "device-select", //类型
            trigger: "change",
            required: true,
            disabled: false,
            span: 8,
            methods: (data, formData) => {
              let arr = data.map((item) => {
                const obj = {
                  equipmentId: item.id,
                  equipmentName: item.name,
                };
                return obj;
              });
              this.$refs.editForm.setFormItem("equipments", arr);
              let form = { equipmentId: data[0].id, typeId: data[0].typeId };
              this.setDeptManage(form);
            },
          },
          {
            label: "设备管理单位",
            prop: "deptManageName",
            type: "text",
            required: true,
            disabled: true,
            span: 8,
          },
          {
            label: "计划起止时间",
            prop: "planStartTime",
            type: "datetimerange",
            required: true,
            disabled: false,
            span: 8,
            methods: (val) => {
              let timers = new Date(val[0]).getTime() - 7 * 24 * 60 * 60 * 1000;
              let remindTime = this.$utils.TimeFormat(timers, 3);
              this.$refs.editForm.setFormItem("startTime", val[0]);
              this.$refs.editForm.setFormItem("endTime", val[1]);
              this.$refs.editForm.setFormItem("remindTime", remindTime);
            },
          },
          {
            label: "主办单位",
            prop: "organizerName",
            propArr: "organizerArr",
            idsStr: "organizer",
            level: "3", //组织层级筛选 2.部门 3.单位
            multiple: false, //是否多选
            allowCreate: true, //是否允许创建条目
            option: this.deptOption, //this.deptOption
            defaultIds: [], //传入需要禁用的id数组
            type: "dept-select", //类型
            trigger: "change",
            required: true,
            methods: (obj) => {},
            span: 8,
          },
          {
            label: "提醒时间",
            prop: "remindTime",
            type: "datetime",
            isHide: false,
            disabled: false,
            required: true,
            min: 0,
            span: 8,
          },
          {
            label: "工作内容",
            prop: "content",
            type: "textarea",
            required: true,
            span: 24,
            rows: 4,
          },
          {
            label: "备注",
            prop: "desc",
            type: "textarea",
            disabled: false,
            span: 24,
            rows: 4,
          },
        ],
      },
      //弹出框表单数据
      editFormData: {},
      rowIndex: 0,
      dialogType: "add",
    };
  },
  watch: {
    depts: {
      handler(val) {
        this.baseTableSetting.data = val.issues;
      },
      deep: true,
    },
    hideBtn: {
      handler(val) {
        this.formConfig.itemArr.forEach((i) => (i.disabled = val));
        this.overhaulConfig.itemArr.forEach((i) => (i.disabled = val));
      },
    },
  },
  created() {
    this.baseTableSetting.data = this.depts.issues;
    if (this.hideBtn) {
      this.formConfig.itemArr.forEach((i) => (i.disabled = true));
      this.overhaulConfig.itemArr.forEach((i) => (i.disabled = true));
    }
  },
  methods: {
    //新建计划
    addPlan(command) {
      this.dialogType = "add";
      this.editFormData = {};
      if (command == 0) {
        this.title = "大修计划";
        this.editFormData.jobType = "overhaul";
      } else if (command == 1) {
        this.title = "试验计划";
        this.editFormData.jobType = "experiment";
      } else {
        this.title = "计划性检修计划";
        this.editFormData.jobType = "repair";
      }
      this.show = true;
    },
    //编辑自定义参数
    editBaseParam(row) {
      this.dialogType = "edit";
      this.title =
        this.$store.getters.fineDirtDataName("plan_package_type", row.jobType) +
        "计划";
      this.show = true;
      setTimeout(() => {
        this.handleFormData(row);
      }, 100);
    },
    //获取设备的设备管理单位
    async setDeptManage(form) {
      let res = await getPresetParamsApi(form);
      let deptObj = res.data["0005000"] || {};
      let { paramResult, paramValue } = deptObj;
      this.$refs.editForm.setFormItem("deptManageName", paramValue);
      this.$refs.editForm.setFormItem("deptManage", paramResult);
    },
    //处理表单数据
    handleFormData(val) {
      let data = JSON.parse(JSON.stringify(val));
      data.planStartTime = [data.startTime, data.endTime];
      data.equipmentName = data.equipments
        .map((i) => i.equipmentName)
        .join(", ");
      data.equipmentId = data.equipments.map((i) => i.equipmentId).join(", ");
      let equipmentOption = data.equipments.map((i) => {
        let obj = {
          label: i.equipmentName,
          value: i.equipmentId,
          id: i.equipmentId,
          name: i.equipmentName,
        };
        return obj;
      });
      let equipmentArr =
        data.jobType == "overhaul"
          ? data.equipments[0].equipmentId
          : data.equipments.map((i) => i.equipmentId);
      this.editFormData = data;
      this.$refs.editForm.setItemOption("equipmentName", equipmentOption);
      setTimeout(() => {
        this.$refs.editForm.setFormItem("equipmentArr", equipmentArr);
      }, 0);
      if (data.jobType == "overhaul") {
        let organizerArr = data.organizer;
        let organizaOption = [
          {
            label: data.organizerName,
            value: data.organizer,
            id: data.organizer,
            name: data.organizerName,
          },
        ];
        this.$refs.editForm.setItemOption("organizerName", organizaOption);
        setTimeout(() => {
          this.$refs.editForm.setFormItem("organizerArr", organizerArr);
        }, 0);
      } else {
        let deptArr = data.deptManage;
        let deptOption = [
          {
            label: data.deptManageName,
            value: data.deptManage,
            id: data.deptManage,
            name: data.deptManageName,
          },
        ];
        this.$refs.editForm.setItemOption("deptManageName", deptOption);
        setTimeout(() => {
          this.$refs.editForm.setFormItem("deptArr", deptArr);
        }, 0);
      }
    },
    //提交表单
    async doSubmit() {
      try {
        let row = await this.$refs.editForm.getFormData();
        if (this.dialogType == "add") {
          this.baseTableSetting.data.push(row);
        } else {
          this.baseTableSetting.data.splice(this.rowIndex, 1, row);
        }
        this.$emit("planListChange", this.baseTableSetting.data);
        this.show = false;
      } catch (error) {
        this.$message.warning(error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  .add {
    text-align: left;
  }
}
</style>
